# -*- coding: utf-8 -*-
import requests
# import re
# import xlwt
# import xlrd
# import pickle
from bs4 import BeautifulSoup
# import json
from Performance import models


# python2 和 python3的兼容代码
try:
    import cookielib

    print(f"user cookielib in python2.")
except:
    import http.cookiejar as cookielib

    print(f"user cookielib in python3.")



# session代表某一次连接
orviboSession = requests.session()
# 因为原始的session.cookies 没有save()方法，所以需要用到cookielib中的方法LWPCookieJar，这个类实例化的cookie对象，就可以直接调用save方法。

userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
header = {
    "Referer": "http://wiki.orvibo.com:8190/login.action?os_destination=%2Fpages%2Fviewpage.action%3FpageId%3D43352241&permissionViolation=true",
    'User-Agent': userAgent,
}


def writeFile(fileName, data, extension='txt'):
    f = open(fileName + '.' + extension, 'wb')
    f.truncate()
    # f.write((data.encode("utf-8")))
    f.write((''.join(data).encode("utf-8")))
    f.close()


def loginOrviboWiki(account, password):
    print("开始模拟登陆Confluence")
    # postUrl = "http://wiki.orvibo.com:8190/dologin.action"
    postUrl = "http://wiki.orvibo.com:8189/login.jsp"
    postData = {
        "os_username": account,
        "os_password": password,
        "login": "登录",
        "os_destination": "/pages/viewpage.action?pageId=47251585"
    }
    # 使用session直接post请求
    responseRes = orviboSession.post(postUrl, data=postData, headers=header)

    print("post登录请求:\n")
    print(responseRes)

    # url = "http://wiki.orvibo.com:8189/issues/?filter=14519"
    # url = "http://wiki.orvibo.com:8190/pages/viewpage.action?pageId=47251585"

    # writeFile('4444', html, 'html')



def saveBugToDb(list):

    # f = open('5555.txt', 'w')
    for dic in list:
        bug = models.Bug()
        bug.bugNo = dic['bugNo']
        bug.priority = dic['priority']
        bug.score = dic['score']
        bug.title = dic['title']
        bug.label = dic['label']
        bug.label1 = dic['label1']
        bug.label2 = dic['label2']
        bug.person = dic['person']
        bug.sprint = dic['sprint']
        bug.version = dic['version']
        bug.save()
    #     f.write(json.dumps(dic, ensure_ascii=False))
    #     f.write('\n')
    # f.close()


def parseCnblog():
    version = '3.3'

    url = 'http://www.cnblogs.com/daiweilai/p/4234336.html'

    list = parse(url,version)

    # print('{}版本Bug总数为：{}'.format(version, len(list)))
    return list
    # bugNo = models.IntegerField(primary_key=True, unique=True)
    # priority = models.IntegerField()
    # title = models.CharField(max_length=512)
    # label = models.CharField(max_length=128)
    # label1 = models.CharField(max_length=128)
    # label2 = models.CharField(max_length=128)
    # person = models.CharField(max_length=128)
    # sprint = models.CharField(max_length=256)
    # version = models.CharField(max_length=128)

    # f = open('5555.txt', 'wb')
    # print('3.3 bug 总数为：',len(list))

def parseBug():

    url = 'http://wiki.orvibo.com:8189/issues/?filter=15203';
    loginOrviboWiki()

def parse(url,version):

    html = orviboSession.get(url, headers=header, allow_redirects=True).text
    soup = BeautifulSoup(html, 'html.parser')

    # print(soup.text)
    next = soup.find(id='post_next_prev')

    print(next.title)
    # print(next.parents)
    return ;
    buglist = soup.find('tbody').children

    # for idx, li in enumerate(td.div.ul.contents):
    bugs = []
    for cols in buglist:
        # 找出其中一行
        if cols.name == 'tr':
            dic = {}
            for td in cols.contents:

                if td.name == 'td': # 找出其中一列
                    name = td['class'][0]
                    if name == "issuekey":  # 找出Bug编号
                        bugNo = td.a['title']
                        dic['bugNo'] = bugNo
                    elif name == "priority":  # 找出Bug等级
                        priority = td.img['alt']

                        if priority == '致命':
                            dic['priority'] = 1
                            dic['score'] = -20
                        elif priority == '严重':
                            dic['priority'] = 2
                            dic['score'] = -15
                        elif priority == '一般':
                            dic['priority'] = 3
                            dic['score'] = -10
                        else:
                            dic['priority'] = 4
                            dic['score'] = -5

                    elif name == "summary":  # 找出Bug标题
                        title = td.p.a.string
                        dic['title'] = title
                    elif name =="labels":  # 找出Bug标签
                        idx = 0
                        # for idx,li in enumerate(td.div.ul.contents):
                        dic['label'] = ''
                        dic['label1'] = ''
                        dic['label2'] = ''
                        if td.div.ul:
                            for li in td.div.ul.contents:
                                if li.name == 'li':
                                    label = li.a['title']
                                    if idx == 0:
                                        dic['label'] = label
                                    elif idx == 1:
                                        dic['label1'] = label
                                    else:
                                        dic['label2'] = label
                                    idx = idx + 1
                    elif name =="customfield_10200":  # 找出解决人
                        if td.contents:
                            person = td.span.a.string
                            dic['person'] = person
                        else:
                            dic['person'] = ''
                    elif name == "customfield_10001":  # 找出sprint
                        sprint = td.string
                        dic['sprint'] = sprint
            if dic['label'] == '替他人解决' or dic['label1'] == '替他人解决' or dic['label2'] == '替他人解决':
                if dic['priority'] == 1:
                    dic['score'] = 30
                elif dic['priority'] == 2:
                    dic['score'] = 15
                elif dic['priority'] == 3:
                    dic['score'] = 10
                else:
                    dic['score'] = 5

            dic['version'] = version
            bugs.append(dic)
    return bugs


if __name__ == "__main__":
    parseCnblog()
